﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;

namespace NearForums.DataAccess
{
    public class AskAnswersDataAccess : BaseDataAccess, IAskAnswersDataAccess
    {

        public void Add(Answers answer, int questionID, int userId)
        {
            DbCommand comm = this.GetCommand("SPAnswerInsert");
            comm.AddParameter(this.Factory, "q_ID", DbType.Int32, questionID);
            comm.AddParameter(this.Factory, "answer", DbType.String, answer.Answer);
            comm.AddParameter(this.Factory, "userID", DbType.Int32, userId);

            comm.ExecuteNonQuery();
        }

        public void Delete(int answerID)
        {
            DbCommand comm = this.GetCommand("SPAnswersDelete");
            comm.AddParameter(this.Factory, "answerID", DbType.Int32, answerID);
            
            comm.ExecuteNonQuery();
        }

        public List<Answers> GetAnswersByQuestion(int questionID)
        {
            DbCommand comm = GetCommand("SPAnswerGetByQuestion");
            comm.AddParameter(this.Factory, "q_ID", DbType.Int32, questionID);

            DataTable dt = GetTable(comm);

            List<Answers> answerList = new List<Answers>();
            foreach (DataRow dr in dt.Rows)
            {
                Answers answer = ParseAnswersDataRow(dr);
                answerList.Add(answer);
            }

            return answerList;
        }

        public void UpdateAnswerStatus(int answerID, int vote, Boolean isBest)
        {
            DbCommand comm = this.GetCommand("SPAnswerStatusUpdate");

            comm.AddParameter(this.Factory, "voted", DbType.Int32, vote);
            comm.AddParameter(this.Factory, "isBest", DbType.Boolean, isBest);
            comm.AddParameter(this.Factory, "answanswerID", DbType.Int32, answerID);

            comm.ExecuteNonQuery();
        }

        protected virtual Answers ParseAnswersDataRow(DataRow dr)
        {
            Answers a = new Answers();
            a.ID = dr.Get<int>("answerID");
            a.Question = new Questions(dr.Get<int>("q_ID"));
            a.Answer = dr.Get<string>("answer");
            a.AnswerDate = dr.GetDate("answerDate");
            a.IsBest = dr.Get<Boolean>("isBest");
            a.User = new User();
            a.User.Id = dr.Get<int>("userID");

            return a;
        }
    }
}
